package com.apache.ius.common;

import com.apache.database.constant.SpringContextLoader;
import com.apache.ius.common.annotion.PkgScanner;
import com.apache.ius.common.annotion.SpringHandlerInterceptor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.*;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * description: 拦截器配置实现类
 *
 * @author dyh 创建时间：2018年07月02日
 */
@Configuration
public class WebInterceptorConfig implements  WebMvcConfigurer {

    private final String PACK_PATH = "com.apache.ius.interceptor";
    /**
     * 自己定义的拦截器类
     * @return
     */
    private List<String> customInterceptor() {
        try {
            PkgScanner scanner = new PkgScanner(PACK_PATH, SpringHandlerInterceptor.class);
            return scanner.scan();
        }catch (IOException e){
            return null;
        }
    }

    @Override
    public void configurePathMatch(PathMatchConfigurer pathMatchConfigurer) {

    }

    @Override
    public void configureContentNegotiation(
            ContentNegotiationConfigurer contentNegotiationConfigurer) {

    }

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer asyncSupportConfigurer) {

    }

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer defaultServletHandlerConfigurer) {

    }

    @Override
    public void addFormatters(FormatterRegistry formatterRegistry) {

    }

    /**
     * 添加拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> interceptors = customInterceptor();
        if(null != interceptors){
            for(int i=0;i<interceptors.size();i++){
                String name = interceptors.get(i);
                try {
                    Class clazz = Class.forName(name);
                    HandlerInterceptor handlerInterceptor = (HandlerInterceptor)clazz.newInstance();
                    SpringHandlerInterceptor annotation = AnnotationUtils
                            .findAnnotation(handlerInterceptor.getClass(), SpringHandlerInterceptor.class);
                    Field[] fields = clazz.getSuperclass().getDeclaredFields();
                    for (Field field : fields) {
                        Qualifier qualifier = field.getAnnotation(Qualifier.class);
                        if(qualifier != null){
                            field.set(handlerInterceptor, SpringContextLoader.getBean(qualifier.value()));
                        }
                    }
                    fields = clazz.getFields();
                    for (Field field : fields) {
                        Qualifier qualifier = field.getAnnotation(Qualifier.class);
                        if(qualifier != null){
                            field.set(handlerInterceptor, SpringContextLoader.getBean(qualifier.value()));
                        }
                    }
                    InterceptorRegistration registration = registry.addInterceptor(handlerInterceptor);

                    String[] includePatterns = getIncludePatterns(annotation);
                    if (includePatterns.length != 0) {
                        registration.addPathPatterns(includePatterns);
                    }
                    String[] excludePatterns = getExcludePatterns(annotation);
                    if (excludePatterns.length != 0) {
                        registration.excludePathPatterns(excludePatterns);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry resourceHandlerRegistry) {

    }

    @Override
    public void addCorsMappings(CorsRegistry corsRegistry) {

    }

    @Override
    public void addViewControllers(ViewControllerRegistry viewControllerRegistry) {

    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry viewResolverRegistry) {

    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> list) {

    }

    @Override
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> list) {

    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> list) {

    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> list) {

    }

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> list) {

    }

    @Override
    public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> list) {

    }

    @Override
    public Validator getValidator() {
        return null;
    }

    @Override
    public MessageCodesResolver getMessageCodesResolver() {
        return null;
    }

    private String[] getIncludePatterns(SpringHandlerInterceptor annotation) {
        List<String> list = new ArrayList<>();
        list.addAll(Arrays.asList(annotation.includePatterns()));
        return list.toArray(new String[] {});
    }

    private String[] getExcludePatterns(SpringHandlerInterceptor annotation) {
        List<String> list = new ArrayList<>();
        list.addAll(Arrays.asList(annotation.excludePatterns()));
        return list.toArray(new String[] {});
    }
}
